#!/usr/bin/env python2
#-*- coding: utf-8 -*-

from Umpweb.common import utils
from Umpweb.common.utils import xx, yy, get_current_user, conv_float
from Umpweb.common.utils import login_required
from Umpweb.common.utils import str_list,str2list
from Umpweb.common.exception import NoAvailableEdog 
from Umpweb.common import oem_conf
from Umpweb.common import log

from Umpweb.db import api as db_api
from sqlalchemy.orm.exc import NoResultFound

import os
import re
import json
import time
import sys
import cgi
import web
import uuid
import httplib2
import httplib
import traceback
import subprocess
import datetime
from Umpweb.base import render_jinja
from Umpweb.base import session, _, render_jinja


LOG = log.get_log('Umpweb.webapps.cluster')


render = render_jinja('static/templates/cluster', encoding='utf-8',)
#app = web.application(urls, locals())


class Cluster:
    def __init__(self):
        pass

    def POST(self):
        x = web.input()
        node_ip = x.get('node_ip','').strip()
        values = {
                'cluster_type':x.get('type'),
                 'passwd':x.get('password','').strip(),
                'node_ip':node_ip,
                'option':x.option.strip(), 
                'name':x.name.strip()}

        web.header("Content-Type", "application/json")

        option = u'无效操作'
        body = {}
        if x.option.strip() == 'import':
            option = u'导入' 
            detail = u'%s集群(%s)失败,'%(option,node_ip)
            msg_option = "ClusterImport"

        if x.option.strip() == 'create':
            option = u'创建'
            detail = u'%s集群失败,'%option
            msg_option = "ClusterCreate"

        pp_id = None
        try:
            body = {msg_option:{'params':values}}
            reply = web.config._server.api_sync_call(body)
            data = json.loads(reply)
        except Exception, e:
            traceback.print_exc()
            return utils.exception2json(e)
        return reply


class ClusterCreate:
    @login_required
    def GET(self):
        x = web.input()
        option = 'create'
        today = datetime.date.today()
        month = str(today.month).zfill(2)
        oem = oem_conf.oem
        return render.cluster_create_page(option=option,today=today,month=month,oem=oem)

    @login_required
    def POST(self):
        pass


class ClusterImport:
    @login_required
    def GET(self):
        x = web.input()
        option = 'import'
        today = datetime.date.today()
        month = str(today.month).zfill(2)
        oem = oem_conf.oem
        return render.cluster_import_page(option=option,today=today,month=month,oem=oem)

    @login_required
    def POST(self):
        pass

class ClusterList:
    @login_required
    def GET(self):
        return render.cluster_list_page()

class ClusterPage:
    @login_required
    def GET(self):
        return render.cluster_page()

class GridCluster:
    @login_required
    def GET(self):
        web_input = web.input()
        page,total,records,rows = utils.grid_rows_query(db_api.cluster_table,web_input)
        LOG.info('%s %s %s %s' % (page,total,records,rows))
        for cluster in rows:
            clusterhosts = db_api.host_get_with_cluster(cluster.id)
            cluster.nodes = len(clusterhosts) 
        cells = ['id', 'name', 'cluster_name', 'nodes', 'usage', 'iscsi_port', 'iqn']
        rows_json = utils.grid_json(page,total,records,rows,'id',cells)
        web.header("Conten-Type","application/json")
        return rows_json


class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)

class GetIopsDay:
    def GET(self,_id):
        cluster = db_api.cluster_get(_id)
        iops = db_api.iops_get_with_cluster_status(cluster.id,'day')
        web.header("Content-Type", "application/json")
        return iops._iops_data if iops else []

class Get_iops_week:
    def GET(self,id):
        cluster = db_api.cluster_get(id)
        iops = db_api.iops_get_with_cluster_status(cluster.id,'week')
        web.header("Content-Type", "application/json")
        return iops._iops_data if iops else []

class Get_iops_month:
    def GET(self,id):
        cluster = db_api.cluster_get(id)
        iops = db_api.iops_get_with_cluster_status(cluster.id,'month')
        web.header("Content-Type", "application/json")
        return iops._iops_data if iops else []

class Get_read:
    def GET(self,id):
        cluster = db_api.cluster_get(id)
        iops = db_api.iops_get_with_cluster_status(cluster.id,'day')
        web.header("Content-Type", "application/json")
        return iops._read_data if iops else []
    
class Get_read_week:
    def GET(self,id):
        cluster = db_api.cluster_get(id)
        iops = db_api.iops_get_with_cluster_status(cluster.id,'week')
        web.header("Content-Type", "application/json")
        return iops._read_data 
    
class Get_read_month:
    def GET(self,id):
        cluster = db_api.cluster_get(id)
        iops = db_api.iops_get_with_cluster_status(cluster.id,'month')
        web.header("Content-Type", "application/json")
        return iops._read_data
    
class Get_write:
    def GET(self,id):
        cluster = db_api.cluster_get(id)
        iops = db_api.iops_get_with_cluster_status(cluster.id,'day')
        web.header("Content-Type", "application/json")
        return iops._write_data

class Get_write_week:
    def GET(self,id):
        cluster = db_api.cluster_get(id)
        iops = db_api.iops_get_with_cluster_status(cluster.id,'week')
        web.header("Content-Type", "application/json")
        return iops._write_data
    
class Get_write_month:
    def GET(self,id):
        cluster = db_api.cluster_get(id)
        iops = db_api.iops_get_with_cluster_status(cluster.id,'month')
        cluster.write_data = json.loads(iops._write_data)
        web.header("Content-Type", "application/json")
        return iops._write_data
    
class Get_swallow_spit:
    def GET(self,id):
        cluster = db_api.cluster_get(id)
        iops = db_api.iops_get_with_cluster_status(cluster.id,'day')
        web.header("Content-Type", "application/json")
        return iops._swallow_spit_data if iops else []

class Get_swallow_spit_week:
    def GET(self,id):
        cluster = db_api.cluster_get(id)
        iops = db_api.iops_get_with_cluster_status(cluster.id,'week')
        cluster.swallow_spit_data = json.loads(iops._swallow_spit_data)
        web.header("Content-Type", "application/json")
        return iops._swallow_spit_data

class Get_swallow_spit_month:
    def GET(self,id):
        cluster = db_api.cluster_get(id)
        iops = db_api.iops_get_with_cluster_status(cluster.id,'month')
        cluster.swallow_spit_data = json.loads(str(iops._swallow_spit_data))
        web.header("Content-Type", "application/json")
        return iops._swallow_spit_data

class Get_swallow:
    def GET(self,id):
        cluster = db_api.cluster_get(id)
        iops = db_api.iops_get_with_cluster_status(cluster.id,'day')
        web.header("Content-Type", "application/json")
        return iops._swallow_data

class Get_swallow_week:
    def GET(self,id):
        cluster = db_api.cluster_get(id)
        iops = db_api.iops_get_with_cluster_status(cluster.id,'week')
        web.header("Content-Type", "application/json")
        return iops._swallow_data

class Get_swallow_month:
    def GET(self,id):
        cluster = db_api.cluster_get(id)
        iops = db_api.iops_get_with_cluster_status(cluster.id,'month')
        web.header("Content-Type", "application/json")
        return iops._swallow_data

class Get_spit:
    def GET(self,id):
        cluster = db_api.cluster_get(id)
        iops = db_api.iops_get_with_cluster_status(cluster.id,'day')
        web.header("Content-Type", "application/json")
        return iops._spit_data

class Get_spit_week:
    def GET(self,id):
        cluster = db_api.cluster_get(id)
        iops = db_api.iops_get_with_cluster_status(cluster.id,'week')
        web.header("Content-Type", "application/json")
        return iops._spit_data

class Get_spit_month:
    def GET(self, id):
        cluster = db_api.cluster_get(id)
        iops = db_api.iops_get_with_cluster_status(cluster.id,'month')
        web.header("Content-Type", "application/json")
        return iops._spit_data


def get_io_val(cluster_id, unit):
    '''unit: day, week, month
    '''
    iops = db_api.iops_get_with_cluster_status(cluster_id, unit)
    res = ['0'] * 8
    if iops:
        swallow_spit,iops_spit,iops_swallow = iops._swallow_spit,iops._spit,iops._swallow
        iops_,iops_read,iops_write = iops._iops,iops._iops_read,iops._iops_write
        res =[iops_, iops_read, iops_write, swallow_spit, iops_swallow, iops_spit]
        res = [str(i) for i in res]
    latency = db_api.latency_get_with_cluster(cluster_id)
    if latency:
        res.append(latency.read_latency_val)
        res.append(latency.write_latency_val)
    return json.dumps(res)


class Get_iops_val:

    def GET(self,id):
        web.header("Content-Type", "application/json")
        LOG.info(get_io_val(id, 'day'))
        return get_io_val(id, 'day')


class Get_iops_val_week:

    def GET(self,id):
        web.header("Content-Type", "application/json")
        return get_io_val(id, 'week')


class Get_iops_val_month:

    def GET(self,id):
        web.header("Content-Type", "application/json")
        return get_io_val(id, 'month')


class LatencyBase(object):

    def latency_data(self, id, attrname):
        latency = db_api.latency_get_with_cluster(id)
        data = []
        if latency:
            data = getattr(latency, attrname)
            data = json.loads(data)
        return data


class GetLatency(LatencyBase):

    def GET(self, id):
        cluster = db_api.cluster_get(id)
#        vlatencies = db_api.volume_latency_get()
        web.header("Content-Type", "application/json")
        return self.latency_data(id, 'read_latency_data')


class GetReadLatency(LatencyBase):

    def GET(self, id):
        cluster = db_api.cluster_get(id)
        web.header("Content-Type", "application/json")
        latency = db_api.latency_get_with_cluster(id)
        return self.latency_data(id, 'read_latency_data')


class GetWriteLatency(LatencyBase):

    def GET(self, id):
        cluster = db_api.cluster_get(id)
        web.header("Content-Type", "application/json")
        latency = db_api.latency_get_with_cluster(id)
        return self.latency_data(id, 'write_latency_data')
